package com.houor.device.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.houor.data.DataReportHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DataServer implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(DataServer.class);

	private int port;
	
	public static boolean flag = true;

	public DataServer(int port) {
		this.port = port;
	}

	public void run() {
		// set server NIO threads group
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup);
			bootstrap.channel(NioServerSocketChannel.class); // (3)
			bootstrap.childHandler(new DataServerInitializer());
			bootstrap.option(ChannelOption.SO_BACKLOG, 128); // (5)
			bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

			// Bind and start to accept incoming connections.
			ChannelFuture channelFuture = bootstrap.bind(port).sync(); // (7)
			if (channelFuture.isSuccess()) {
				logger.debug("Server is starting...");
			}

			// Wait until the server socket is closed.
			// At here, this does not happen, but we can do that to
			// gracefully shut down your server.
			channelFuture.channel().closeFuture().sync();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// shutdown gracefully, and release thread poll
			flag = false;
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
			logger.debug("Server is ended gracefully.");
		}
	}

	public static void main(String[] args) {

		DataServer server = new DataServer(12071);
		DataReportHandler drh = new DataReportHandler();
		try {
			Thread drhThread = new Thread(drh);
			drhThread.setDaemon(true);
			drhThread.start();
			new Thread(server).run();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
